package Demo1;

import java.util.HashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 34255
 * Date: 2024-09-02
 * Time: 19:19
 */
public class Test {

    //最多K个重复元素的最长子数组
    public int maxLength = 0;
    public int maxSubarrayLength(int[] nums, int k) {
        Map<Integer,Integer> map = new HashMap<>();
        int i = 0;
        int j = 0;
        for (; j < nums.length; j++) {
            int count = map.getOrDefault(nums[j],0);
            map.put(nums[j],count + 1);
            if(count + 1 > k && maxLength < j - i){
                maxLength = j - i;
            }
            while(map.get(nums[j]) > k){
                map.put(nums[i],map.get(nums[i]) - 1);
                i++;
            }
        }
        if(j - i > maxLength) maxLength = j - i;
        return maxLength;
    }
    
    public static void main(String[] args) {
        int[] array = {1,4,4,3};
        int k = 1;
        Test test = new Test();
        int ret = test.maxSubarrayLength(array,k);
        System.out.println(ret);
    }
}
